package com.jishuo.nontax.bfc.service;

import com.github.pagehelper.PageHelper;
import com.jishuo.base.bean.BaseResult;
import com.jishuo.base.bean.ErrorCodeEnum;
import com.jishuo.base.bean.Pagination;
import com.jishuo.base.config.NonTaxConfig;
import com.jishuo.base.dao.UserMapper;
import com.jishuo.base.service.SequenceService;
import com.jishuo.base.util.ExportSXSSFUtil;
import com.jishuo.base.util.GTimeUtil;
import com.jishuo.nontax.bean.message.CleanBankCheckBill;
import com.jishuo.nontax.bean.vo.*;
import com.jishuo.nontax.bfc.dao.*;
import com.jishuo.nontax.bfc.tlq.MessageFactory;
import com.jishuo.nontax.bfc.tlq.MessageService;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 预审对账服务
 * @author hlp
 * @date 2023/2/16 10:41
 */
@Service
public class BankCheckBillService {

    private static Logger logger = LoggerFactory.getLogger(BankCheckBillService.class);

    @Resource
    private BankCheckBillMapper bankCheckBillMapper;
    @Resource
    private SequenceService sequenceService;
    @Resource
    private BankMapper bankMapper;
    @Resource
    private MessageService messageService;
    @Resource
    private NonTaxConfig nonTaxConfig;
    @Resource
    private PreerrMapper preerrMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private BankBalanceService bankBalanceService;
    @Resource
    private WaitaffirmService waitaffirmService;
    @Resource
    private WaitaffirmPayInfoService waitaffirmPayInfoService;
    @Resource
    private DeductService deductService;
    @Resource
    private BankBalanceMapper bankBalanceMapper;
    @Resource
    private TaskService taskService;
    @Resource
    private MessageSysMapper messageSysMapper;
    @Resource
    private BankCheckMapper bankCheckMapper;
    @Resource
    private ChargeBillService chargeBillService;
    @Resource
    private PunishService punishService;
    @Resource
    private IllegalactivityinfoService illegalactivityinfoService;
    @Resource
    private DivideService divideService;
    @Resource
    private FiscService fiscService;
    @Resource
    private StudentService studentService;
    @Resource
    private SpecialService specialService;
    @Resource
    private PayScaleBillService payScaleBillService;
    @Resource
    private BackBillService backBillService;

    /**
     * 预审结果分页查询
     * @param preresultsVO 条件，bankid，paybankdt
     * @param pagination 分页
     * @return
     */
    public List<PreresultsVO> findPrereSultsPage(PreresultsVO preresultsVO, Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return preerrMapper.findPrereSultsPage(preresultsVO);
    }

    /**
     * @author hlp
     * @date 2023/3/16 09:20
     * @Description:  对账信息发送详情列表分页
     */
    public List<BankCheckBillVO> findBankCheckBillPage(BankCheckBillVO bankCheckBillVO, Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return this.bankCheckBillMapper.findBankCheckBill(bankCheckBillVO);
    }

    public List<BankCheckBillVO> selwebpayPage(BankCheckBillVO bankCheckBillVO, Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return this.bankCheckBillMapper.selwebpay(bankCheckBillVO);
    }


    /**
     * @author hlp
     * @date 2023/3/16 09:20
     * @Description:  财政对账分页
     */
    public List<PreerrVO> findPreerrPage(PreerrVO preerrVO, Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return preerrMapper.findPreerrPage(preerrVO);
    }
    @Resource
    private BankCheckResultMapper bankCheckResultMapper;

    /**
     * @author hlp
     * @date 2023/12/11 11:37
     * @Description: 内部对账分页
     */
    public List<CheckResultVO> findBankCheckResult(String paybankdt, Pagination pagination) {
        // 当单页条数大于零时，启用分页
        if (pagination.getRows() > 0) PageHelper.startPage(pagination.getPage(), pagination.getRows());
        return bankCheckResultMapper.findBankCheck(paybankdt);
    }

    public List<PreerrVO> findBankCheckDetail(PreresultsVO preresultsVO) {
        return preerrMapper.findBankCheckDetail(preresultsVO);
    }


    /**
     * @param bankCheckBill 对账流水对象
     * @auther dinggaofei
     * @Date 2022/12/21 8:45
     * @description 添加修改 记录对账流水信息
     */
    public BaseResult setBankCheckBill(BankCheckBillVO bankCheckBill) {
        try {
            if (bankCheckBillMapper.selectBankCheckBillCount(bankCheckBill.getBankcheckid(), bankCheckBill.getAccountnum(), bankCheckBill.getAccountdate()) > 0) {
                if (bankCheckBillMapper.updateBankCheckBill(bankCheckBill) > 0) {
                    return new BaseResult();
                }
            } else {
                if (bankCheckBillMapper.insertBankCheckBill(bankCheckBill) > 0) {
                    return new BaseResult();
                }
            }
            return new BaseResult(ErrorCodeEnum.DB_ERR);
        } catch (Exception e) {
            logger.info("处理失败：" + e.toString());
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }


    /**
     * @param accountcode 账户
     * @Param accountdate  收款时间
     * @auther dinggaofei
     * @Date 2022/12/21 9:30
     * @description 查询对账流水信息 上传到财政
     */
    public BaseResult sendBankCheckBill(String accountcode, String accountdate) {
        try {
            List<BankCheckBillVO> list =bankCheckBillMapper.findSendBankCheckBill(accountcode, accountdate);

            if (list != null && list.size() > 0) {
                long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");

                Object setBankBillCheck = MessageFactory.getSetBankBillCheck(list);
                //发送到财政
                messageService.sendMessage("SETBANKBILLCHECK", messageid, setBankBillCheck, "2.0");
            }
            return new BaseResult();
        } catch (Exception e) {
            logger.info("发送对账流水失败：" + e.toString(), e);
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }

    /**
     * 清除财政端对账流水
     * @param bankid 账户id
     * @param accountcode 账号
     * @param paybankdt 日期，yyyy-MM-dd
     */
    public BaseResult cleanBankCheck(long bankid, String accountcode, String paybankdt) {
        try {
            if (bankid == 0) {
                BankVO bank = bankMapper.findBankVO(accountcode);
                bankid = bank.getBankid();
            }
            long messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
            if (paybankdt.length() > 10) {
                paybankdt = paybankdt.substring(0, 10);
            }
            CleanBankCheckBill clean = new CleanBankCheckBill();
            clean.setBankaccount(accountcode);
            clean.setBankid(String.valueOf(bankid));
            clean.setPaybankdt(paybankdt);

            //发送到财政
            messageService.sendMessage("CLEANBANKCHECKBILL", messageid, clean, "2.0");

            if (nonTaxConfig.IS_Post) {
                //清除t+1对账
                messageid = sequenceService.getNextSeq("ELEMESSAGESEQ");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar cd = Calendar.getInstance();
                cd.setTime(sdf.parse(paybankdt));
                cd.add(Calendar.DATE, 1);

                String paybankdtup = sdf.format(cd.getTime());
                clean.setPaybankdt(paybankdtup);

                //发送到财政
                messageService.sendMessage("CLEANBANKCHECKBILL", messageid, clean, "2.0");
            }
            return new BaseResult();
        } catch (Exception e) {
            logger.info("发送失败：" + e.toString(), e);
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }

    private int savePreResult(long bankid, String chkDay, BigDecimal inamt, BigDecimal outamt, BigDecimal balance, int state, String memo) {
        // 删除原有的
        preerrMapper.deletePrereSults(bankid, chkDay);
        PreresultsVO preresultsVO = new PreresultsVO(bankid, chkDay, inamt, outamt, balance, state, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), memo);
        return preerrMapper.insertPrereSults(preresultsVO);
    }

    /**
     * 预审实现
     * @param bank 账户对象
     * @param chkDay 对账日
     * @param beforeDay 对账日前一天
     * @return
     */
    public BaseResult check(BankVO bank, String chkDay, String beforeDay) {
        try {
            long bankid = bank.getBankid();
            String accountcode = bank.getAccountcode();
            String accountname = bank.getAccountname();

            if (beforeDay == null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar cal = Calendar.getInstance();
                cal.setTime(sdf.parse(chkDay));
                cal.add(Calendar.DATE, -1);
                beforeDay = sdf.format(cal.getTime());
            }

            String str="&&&&&&\n";
            StringBuilder memo = new StringBuilder();
            // 获取余额
            BigDecimal balance, balanceup;
            List<BankBalanceVO> balList = bankBalanceMapper.findBankBalance(bankid, chkDay);
            if (balList.size() == 0) {
                // 对账失败
                this.savePreResult(bankid, chkDay, BigDecimal.ZERO, BigDecimal.ZERO, new BigDecimal("-1"), 1,
                        "对账失败\n当日余额未填写");
                return BaseResult.CustomErr("当日余额未填写");
            }
            balance = balList.get(0).getFund();
            memo.append("当日余额：").append(balance.toPlainString());
            balList = bankBalanceMapper.findBankBalance(bankid, beforeDay);
            if (balList.size() == 0) {
                // 对账失败
                this.savePreResult(bankid, chkDay, BigDecimal.ZERO, BigDecimal.ZERO, balance, 1,
                        "对账失败\n" + memo.toString() + ",上日余额未填写");
                return BaseResult.CustomErr("上日余额未填写");
            }
            balanceup = balList.get(0).getFund();
            memo.append(",上日余额：").append(balanceup.toPlainString())
                    .append(",差额：").append(balance.subtract(balanceup).toPlainString()).append("\n");

            /*
            -------汇总票据数量、金额
            1一般缴款书；2 退付；3 待查收入；4 pos；5 国库；51 电子缴款；6 专户；7 分成；8 批扣；9 学生
            10 交罚(未分成)；101 交罚（已分成）；11 交管二八汇总；12 交管二八分成；13 通用罚没；14 网银；15 交管跨省；16 99支出；17 电子缴款
             */

            // 统计
            ReconciliationVO tranStat = bankCheckMapper.selectReconciliation(bankid, accountcode, chkDay);
            List<PrereSultsDetailVO> list = new ArrayList<>();
            String wtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            //缴款书
            int num1 = tranStat.getNum1();
            BigDecimal fund1 = (tranStat.getFund1() == null) ? BigDecimal.ZERO : tranStat.getFund1();
            memo.append("缴款书:笔数：").append(num1).append(",金额：").append(fund1.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund1, num1, 1, "缴款书", wtime));

            // 退付
            int num2 = tranStat.getNum2();
            BigDecimal fund2 = (tranStat.getFund2() == null) ? BigDecimal.ZERO : tranStat.getFund2();
            memo.append("退付:笔数：").append(num2).append(",金额：").append(fund2.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund2, num2, 2, "退付", wtime));

            //待查
            int num3 = tranStat.getNum3();
            BigDecimal fund3 = (tranStat.getFund3() == null) ? BigDecimal.ZERO : tranStat.getFund3();
            memo.append("待查:笔数：").append(num3).append(",金额：").append(fund3.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund3, num3, 3, "待查", wtime));

            //POS
            int num4 = tranStat.getNum4();
            BigDecimal fund4 = (tranStat.getFund4() == null) ? BigDecimal.ZERO : tranStat.getFund4();
            memo.append("POS:笔数：").append(num4).append(",金额：").append(fund4.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund4, num4, 4, "POS", wtime));

            //国库
            int num5 = tranStat.getNum5();
            BigDecimal fund5 = (tranStat.getFund5() == null) ? BigDecimal.ZERO : tranStat.getFund5();
            // 电子缴库
            int num51 = tranStat.getNum51();
            BigDecimal fund51 = (tranStat.getFund51() == null) ? BigDecimal.ZERO : tranStat.getFund51();
            memo.append("国库:笔数：").append(num5 + num51).append(",金额：").append(fund5.add(fund51).toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund5, num5, 5, "国库", wtime));

            // 专户
            int num6 = tranStat.getNum6();
            BigDecimal fund6 = (tranStat.getFund6() == null) ? BigDecimal.ZERO : tranStat.getFund6();
            memo.append("专户:笔数：").append(num6).append(",金额：").append(fund6.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund6, num6, 6, "专户", wtime));

            // 分成
            int num7 = tranStat.getNum7();
            BigDecimal fund7 = (tranStat.getFund7() == null) ? BigDecimal.ZERO : tranStat.getFund7();
            memo.append("分成:笔数：").append(num7).append(",金额：").append(fund7.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund7, num7, 7, "分成", wtime));

            // 批扣
            int num8 = tranStat.getNum8();
            BigDecimal fund8 = (tranStat.getFund8() == null) ? BigDecimal.ZERO : tranStat.getFund8();
            memo.append("批扣:笔数：").append(num8).append(",金额：").append(fund8.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund8, num8, 2, "批扣", wtime));

            // 高校
            int num9 = tranStat.getNum9();
            BigDecimal fund9 = (tranStat.getFund9() == null) ? BigDecimal.ZERO : tranStat.getFund9();
            memo.append("高校:笔数：").append(num9).append(",金额：").append(fund9.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund9, num9, 9, "高校", wtime));

            // 交管（未分成）
            int num10 = tranStat.getNum10();
            BigDecimal fund10 = (tranStat.getFund10() == null) ? BigDecimal.ZERO : tranStat.getFund10();
            // 交管（已分成）
            int num10_1 = tranStat.getNum101();
            BigDecimal fund10_1 = (tranStat.getFund101() == null) ? BigDecimal.ZERO : tranStat.getFund101();
            memo.append("交管:笔数：").append(num10 + num10_1).append(",金额：").append(fund10.add(fund10_1).toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund10.add(fund10_1), num10 + num10_1, 10, "交管", wtime));

            BigDecimal fund11 = BigDecimal.ZERO;
            if(bank.getCantonid() == 41){
                //交管二八汇缴
                ReconciliationVO tranStat11 = bankCheckMapper.selectReconciliation11(bankid, accountcode, chkDay);
                int num11 = tranStat11.getNum11();
                fund11 = (tranStat11.getFund11() == null) ? BigDecimal.ZERO : tranStat11.getFund11();
                memo.append("交管二八汇缴:笔数：").append(num11).append(",金额：").append(fund11.toPlainString()).append("\n");
                list.add(new PrereSultsDetailVO(bankid, chkDay, fund11, num11, 11, "交管二八汇缴", wtime));

            }

            //交管二八分成
            int num12 = tranStat.getNum12();
            BigDecimal fund12 = (tranStat.getFund12() == null) ? BigDecimal.ZERO : tranStat.getFund12();
            memo.append("交管二八分成:笔数：").append(num12).append(",金额：").append(fund12.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund12, num12, 12, "交管二八分成", wtime));

            //通用罚没
            int num13 = tranStat.getNum13();
            BigDecimal fund13 = (tranStat.getFund13() == null) ? BigDecimal.ZERO : tranStat.getFund13();
            memo.append("通用罚没:笔数：").append(num13).append(",金额：").append(fund13.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund13, num13, 13, "通用罚没", wtime));

            //网银
            int num14 = tranStat.getNum14();
            BigDecimal fund14 = (tranStat.getFund14() == null) ? BigDecimal.ZERO : tranStat.getFund14();
            memo.append("网银:笔数：").append(num14).append(",金额：").append(fund14.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund14, num14, 14, "网银", wtime));

            //跨省交管
            int num15 = tranStat.getNum15();
            BigDecimal fund15 = (tranStat.getFund15() == null) ? BigDecimal.ZERO : tranStat.getFund15();
            memo.append("跨省交管:笔数：").append(num15).append(",金额：").append(fund15.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund15, num15, 15, "跨省交管", wtime));

            //99支出
            int num16 = tranStat.getNum16();
            BigDecimal fund16 = (tranStat.getFund16() == null) ? BigDecimal.ZERO : tranStat.getFund16();
            memo.append("99支出:笔数：").append(num16).append(",金额：").append(fund16.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund16, num16, 16, "99支出", wtime));

            //电子缴款
            int num17 = tranStat.getNum17();
            BigDecimal fund17 = (tranStat.getFund17() == null) ? BigDecimal.ZERO : tranStat.getFund17();
            memo.append("电子缴款:笔数：").append(num17).append(",金额：").append(fund17.toPlainString()).append("\n");
            list.add(new PrereSultsDetailVO(bankid, chkDay, fund17, num17, 17, "电子缴款", wtime));

            //预审明细入库
            preerrMapper.deleteResultDetail(bankid, chkDay);
            preerrMapper.insertPrereSultsDetail(list);


            //计算金额
            BigDecimal inamt=(fund1.add(fund3).add(fund4).add(fund8).add(fund9).add(fund10).add(fund10_1)
                    .add(fund11).add(fund13).add(fund14).add(fund15).add(fund17));
            BigDecimal outamt=(fund2.add(fund5).add(fund6).add(fund7).add(fund12).add(fund16));

            if (balance.subtract(balanceup).compareTo(inamt.subtract(outamt)) != 0) {
                // 对账失败
                this.savePreResult(bankid, chkDay, inamt, outamt, balance, 1, "对账失败\n" + memo.toString());
                return BaseResult.CustomErr("对账失败");
            }
            // 对账成功
            this.savePreResult(bankid, chkDay, inamt, outamt, balance, 0, "对账成功\n" + memo.toString());

            // -------开始生成对账流水
            // 查询checkbillid，purpose=8、
            String chkid8 = null, chkid9 = null, chkid10 = null, chkid101 = null, chkid11 = null, chkid12 = null, chkid13 = null, chkid15 = null;
            List<BankCheckBillVO> chkids = bankCheckBillMapper.findCheckBillId(accountcode, chkDay);
            for (BankCheckBillVO vo : chkids) {
                if (vo.getPurpose() == 8) chkid8 = vo.getBankcheckid();
                if (vo.getPurpose() == 9) chkid9 = vo.getBankcheckid();
                if (vo.getPurpose() == 10) {
                    if (chkid10 == null) {
                        chkid10 = vo.getBankcheckid();
                    } else {
                        chkid101 = vo.getBankcheckid();
                    }
                }
                if (vo.getPurpose() == 11) chkid11 = vo.getBankcheckid();
                if (vo.getPurpose() == 12) chkid12 = vo.getBankcheckid();
                if (vo.getPurpose() == 13) chkid13 = vo.getBankcheckid();
                if (vo.getPurpose() == 15) chkid15 = vo.getBankcheckid();
            }

            // 删除所有流水
            bankCheckBillMapper.deleteCheckBill(accountcode, chkDay);
            // 生成流水
            bankCheckBillMapper.saveCheckBill_1(bankid, accountcode, accountname, chkDay);
            bankCheckBillMapper.saveCheckBill_2(bankid, accountcode, accountname, chkDay);
            bankCheckBillMapper.saveCheckBill_3(bankid, accountcode, accountname, chkDay);
            bankCheckBillMapper.saveCheckBill_4(bankid, accountcode, accountname, chkDay);
            bankCheckBillMapper.saveCheckBill_5(bankid, accountcode, accountname, chkDay);
            bankCheckBillMapper.saveCheckBill_51(bankid, accountcode, accountname, chkDay);
            bankCheckBillMapper.saveCheckBill_6(bankid, accountcode, accountname, chkDay);
            bankCheckBillMapper.saveCheckBill_7(bankid, accountcode, accountname, chkDay);
            // 批扣，汇总数据。
            bankCheckBillMapper.saveCheckBill_8(bankid, accountcode, accountname, chkDay, this.getCheckBillID(8, chkid8));
            bankCheckBillMapper.saveCheckBill_9(bankid, accountcode, accountname, chkDay, this.getCheckBillID(9, chkid9));
            bankCheckBillMapper.saveCheckBill_10(bankid, accountcode, accountname, chkDay, this.getCheckBillID(10, chkid10));
            bankCheckBillMapper.saveCheckBill_101(bankid, accountcode, accountname, chkDay, this.getCheckBillID(101, chkid101));
            if (bank.getCantonid() == 41) {
                bankCheckBillMapper.saveCheckBill_11(bankid, accountcode, accountname, chkDay, this.getCheckBillID(11, chkid11));
            }
            bankCheckBillMapper.saveCheckBill_12(bankid, accountcode, accountname, chkDay, this.getCheckBillID(12, chkid12));
            bankCheckBillMapper.saveCheckBill_13(bankid, accountcode, accountname, chkDay, this.getCheckBillID(13, chkid13));
            bankCheckBillMapper.saveCheckBill_15(bankid, accountcode, accountname, chkDay, this.getCheckBillID(14, chkid15));

            bankCheckBillMapper.saveCheckBill_16(bankid, accountcode, accountname, chkDay);
            bankCheckBillMapper.saveCheckBill_17(bankid, accountcode, accountname, chkDay);

        } catch (Exception e) {
            logger.info("对账失败[" + bank.getAccountcode() + ", " + chkDay + "]。", e);
            return BaseResult.CustomErr("对账异常");
        }
        return new BaseResult();
    }

    /**
     * 页面请求对账
     * @param bankid
     * @param paybankdt
     * @return
     */
    public BaseResult check(long bankid,String paybankdt) {
        if (bankid < 1 || paybankdt == null || paybankdt.length() != 10) return new BaseResult(ErrorCodeEnum.PARAM_ERR);

        BankVO bank = bankMapper.getBankVo(bankid);
        if (bank == null) return BaseResult.CustomErr("账户不存在");

        return this.check(bank, paybankdt, null);
    }

    /**
     * 预审并发送全部账户，定时任务
     */
    public void autoCheck() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String chkDay = sdf.format(cal.getTime());
        cal.add(Calendar.DATE, -1);
        String beforeDay = sdf.format(cal.getTime());

        List<BankVO> list = bankMapper.bankclasFindBankVo(nonTaxConfig.Sender);
        for (BankVO bank : list) {
            this.check(bank, chkDay, beforeDay);
            this.sendBankCheck(bank.getBankid(), bank.getAccountcode(), chkDay, false);
        }
    }

    /**
     * 发送对账结果
     * @param bankid 账户id
     * @param accountcode 账号
     * @param paybankdt 日期
     * @param manual 是否手工预审，手工时任务财政端已有，删除财政流水时做个延时
     * @return
     */
    public BaseResult sendBankCheck(long bankid,String accountcode, String paybankdt, boolean manual) {
        if (preerrMapper.preCheckSuc(bankid, paybankdt) == 0) return BaseResult.CustomErr("预审失败，不能发送财政");

        cleanBankCheck(bankid, accountcode, paybankdt); // 清除财政端对账流水
        if (manual) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {}
        }
        bankBalanceService.sendBankBalance(bankid, paybankdt, false); // 发送余额
        waitaffirmService.sendWaitAffirm(bankid,paybankdt); // 发送待查
        waitaffirmPayInfoService.sendWaitAffirmPayInfo(bankid, accountcode, paybankdt); // 发送99
        deductService.sendDeduct(accountcode, paybankdt); // 发送批扣
        sendBankCheckBill(accountcode,paybankdt); // 发送对账流水

        return new BaseResult();
    }

    @Resource
    private BankCheckService bankCheckService;

    public BaseResult getcheckdata(long bankid,String paybankdt){
        if(bankid>0 && paybankdt!=null && !paybankdt.trim().equals("")){
            if(isEnableSend(bankid, paybankdt)){
                bankCheckService.getCheckData(bankid,paybankdt);
                return new BaseResult();
            }else{
                return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR.getCode(),"已向财政申请对账数据,相同账户请隔五分钟再提取!");
            }
        }
        return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR.getCode(),"已向财政申请对账数据,请稍等三到五分钟后，查看明细中的对账数据!");
    }

    public boolean isEnableSend(long bankid,String paybankdt){
        // 获得5分钟内的记录
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MINUTE, -5);
        String ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cal.getTime());
        List<String> list = messageSysMapper.isEnableSend(ft);
        String txt = "<bill><bankid>" + bankid + "</bankid><paybankdt>" + paybankdt + "</paybankdt></bill>";
        for (int i=0;i<list.size();i++) {
            try {
                if (list.get(i).indexOf(txt) >= 0) return false;
            } catch(Exception ex) {}
        }
        return true;
    }

    public void findPreerrExport(PreerrVO preerrVO, HttpServletResponse response) throws IOException {
        List<PreerrVO> list = preerrMapper.findPreerrPage(preerrVO);

        String[] headers = {"账户id","账号","开户名称","日期","预审状态","财政对账状态","对账结果"};
        //数据键名或者MODEL类字段名
        String[] col = {"bankid","accountcode","bankname","paybankdt","state","state1","memo"};
        ExportSXSSFUtil ex = new ExportSXSSFUtil();
        SXSSFWorkbook workbook = ex.exportExcelSXSSF("财政对账列表", headers, col, list, null);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String(("财政对账列表.xls").getBytes(), "iso-8859-1"));
        OutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }

    public void findPrereSultsExport(PreresultsVO preresultsVO, HttpServletResponse response) throws IOException {
        List<PreresultsVO> list = preerrMapper.findPrereSultsPage(preresultsVO);
        for (PreresultsVO vo : list) {
            BigDecimal subtract = vo.getInamt().subtract(vo.getOutamt());
            vo.setSubtr(subtract);
        }

        String[] headers = {"账号","开户行名称","日期","余额","当日发生金额","收入金额","支出金额","预审状态"};
        //数据键名或者MODEL类字段名
        String[] col = {"accountcode","bankname","paybankdt","balance","inamt","subtr","outamt","state"};
        ExportSXSSFUtil ex = new ExportSXSSFUtil();
        SXSSFWorkbook workbook = ex.exportExcelSXSSF("对账数据列表", headers, col, list, null);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String(("对账数据列表.xls").getBytes(), "iso-8859-1"));
        OutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }

    public BaseResult autocheck1(String paybankdt){
        try {
            List<BankVO> list = bankMapper.bankclasFindBankVo(nonTaxConfig.Sender);
            for(BankVO bank:list){
                taskService.checkData(bank.getBankid(), paybankdt);
            }
            return new BaseResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new BaseResult(ErrorCodeEnum.UNKNOWN_ERR);
        }
    }

    public BaseResult editWebpay(BankCheckBillVO bankCheckBillVO){
        String accountdate = bankCheckBillVO.getAccountdate();
        bankCheckBillVO.setAccountdate(accountdate.substring(0,10));
        bankCheckBillVO.setAccounttime(accountdate.substring(11,19));
        if(bankCheckBillVO.getBankcheckid()!=null&&bankCheckBillVO.getBankcheckid()!=""){
            if(bankCheckBillMapper.updateWebpay(bankCheckBillVO)>0){
                return new BaseResult();
            }
        }else{
            bankCheckBillVO.setBankcheckid(GTimeUtil.getTime(GTimeUtil.YYYYMMDDhhmmssxxx)+System.currentTimeMillis());
            if(bankCheckBillMapper.insertWebpay(bankCheckBillVO)>0){
                return new BaseResult();
            }
        }
        return new BaseResult(ErrorCodeEnum.DB_ERR);
    }

    public BaseResult deleteWebpay(String bankcheckids){
        if(bankCheckBillMapper.deleteWebpayIds(bankcheckids)>0){
            return new BaseResult();
        }
        return new BaseResult(ErrorCodeEnum.DB_ERR);
    }

    public void webpayExport(BankCheckBillVO bankCheckBillVO, HttpServletResponse response) throws IOException {
        List<BankCheckBillVO> list = bankCheckBillMapper.selwebpay(bankCheckBillVO);

        String[] headers = {"账户名称","账户","银行名称","日期","金额"};
        //数据键名或者MODEL类字段名
        String[] col = {"accountname","accountnum","bankname","accountdate","money"};
        ExportSXSSFUtil ex = new ExportSXSSFUtil();
        SXSSFWorkbook workbook = ex.exportExcelSXSSF("网银缴费列表", headers, col, list, null);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename="+ new String(("网银缴费列表.xls").getBytes(), "iso-8859-1"));
        OutputStream ouputStream = response.getOutputStream();
        workbook.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }

    public BaseResult incheck(String paybankdt){
        try{
            Calendar c = Calendar.getInstance();
            c.setTime(new Date());
            c.set(Calendar.DATE, c.get(Calendar.DATE)-1);
            String paybankdt1 =paybankdt.substring(0,10).replace("-","");
            logger.info("开始内部对账");
            checkindeal(paybankdt1,nonTaxConfig.localpath,paybankdt);
            checkserviceDeal(paybankdt);
            logger.info("结束内部对账");
            return new BaseResult();
        }catch(Exception e){
            e.printStackTrace();
            return new BaseResult("2","");
        }

    }

    public void checkserviceDeal(String paybankdt){
        try {
            bankCheckResultMapper.saveCheckResult1(paybankdt);
        }catch(Exception e) {
            logger.info("内部对账一般缴款书电子票失败："+e.toString());
            e.printStackTrace();
        }
        try {
            bankCheckResultMapper.saveCheckResult2(paybankdt);
        }catch(Exception e) {
            logger.info("内部对账一般缴款书手工票失败："+e.toString());
            e.printStackTrace();
        }
        try {
            bankCheckResultMapper.saveCheckResult3(paybankdt);
        }catch(Exception e) {
            logger.info("内部对账交罚更新失败："+e.toString());
            e.printStackTrace();
        }
        try {
            bankCheckResultMapper.saveCheckResult4(paybankdt);
        }catch(Exception e) {
            logger.info("内部小条缴费更新失败："+e.toString());
            e.printStackTrace();
        }
        try {
            bankCheckResultMapper.saveCheckResult5(paybankdt);
        }catch(Exception e) {
            logger.info("内部化解国库更新失败："+e.toString());
            e.printStackTrace();
        }
        try {
            bankCheckResultMapper.saveCheckResult6(paybankdt);
        }catch(Exception e) {
            logger.info("内部化解专户更新失败："+e.toString());
            e.printStackTrace();
        }
        try {
            bankCheckResultMapper.saveCheckResult7(paybankdt);
        }catch(Exception e) {
            logger.info("内部对账化解分成更新失败："+e.toString());
            e.printStackTrace();
        }
        try {
            bankCheckResultMapper.saveCheckResult8(paybankdt);
        }catch(Exception e) {
            logger.info("内部对账二八分成划转更新失败："+e.toString());
            e.printStackTrace();
        }
        try {
            bankCheckResultMapper.saveCheckResult9(paybankdt);
        }catch(Exception e) {
            logger.info("内部对账退付书更新失败："+e.toString());
            e.printStackTrace();
        }
        try {
            bankCheckResultMapper.saveCheckResult10(paybankdt);
        }catch(Exception e) {
            logger.info("内部对账跨省交罚更新失败："+e.toString());
            e.printStackTrace();
        }
    }

    public void checkindeal(String paybankdt,String path,String paybankdt1){
        try{
            try{
                bankCheckResultMapper.deleteBackBillDepoDt(paybankdt1);
                bankCheckResultMapper.deleteChargeBillDt(paybankdt1);
                bankCheckResultMapper.deleteChargeBillHandDt(paybankdt1);
                bankCheckResultMapper.deleteCheckStudentDt(paybankdt1);
                bankCheckResultMapper.deleteDividePayInfoDt(paybankdt1);
                bankCheckResultMapper.deleteFiscPayInfoDt(paybankdt1);
                bankCheckResultMapper.deleteIllActiScaleDt(paybankdt1);
                bankCheckResultMapper.deleteIllActiviDt(paybankdt1);
                bankCheckResultMapper.deleteIllCrossPayDt(paybankdt1);
                bankCheckResultMapper.deleteResultDt(paybankdt1);
                bankCheckResultMapper.deleteSpePayInfoDt(paybankdt1);
            }catch(Exception e){
                e.printStackTrace();
                logger.info("错误信息="+e);
            }
            String encoding = "GBK";
            for(int i=1;i<=10;i++){
                String filePath="";
                if(i==10){
                    filePath=path+"\\JISHUOCHECK_"+i+"_"+paybankdt+".dat";
                }else{
                    filePath=path+"\\JISHUOCHECK_0"+i+"_"+paybankdt+".dat";
                }
                File file = new File(filePath);
                if (file.isFile() && file.exists()) { //判断文件是否存在
                    InputStreamReader read = new InputStreamReader(
                            new FileInputStream(file), encoding);//考虑到编码格式
                    BufferedReader bufferedReader = new BufferedReader(read);
                    String lineTxt = null;
                    if(i==1){//一般缴款书电子票
                        ChargeBillCheckVO cbv=new ChargeBillCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            //  	String temp=lineTxt.replace(" ","");
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            cbv.setNum(s[0].toString());
                            cbv.setBillnum(s[1].toString());
                            cbv.setEticketnum(s[2].toString());
                            cbv.setPayer(s[3].toString());
                            cbv.setFilldate(s[4].toString());
                            cbv.setAccountcode(s[5].toString());
                            cbv.setIswaitaffirm(Integer.parseInt(s[6].toString()));
                            cbv.setOriginfund(Double.parseDouble(s[7].toString()));
                            cbv.setPaybankdt(s[8].toString());
                            cbv.setBankaffirm(s[9].toString());
                            cbv.setBankstation(s[10].toString());
                            cbv.setPaywaycode(s[11].toString());
                            try{
                                if(cbv.getIswaitaffirm()!=1){
                                    if(bankCheckMapper.findchargebillCount(cbv.getBillnum(), paybankdt1)==0){
                                        if(bankCheckResultMapper.isResult(1,1,cbv.getBillnum(),cbv.getBankstation(),paybankdt1)==0){
                                            long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                            bankCheckResultMapper.insertCheckResult(studentid,cbv.getBillnum(),cbv.getBankstation(),paybankdt1,1,1);
                                        }
                                        BaseResult baseResult = chargeBillService.setChargeBillDeposit(cbv.getChargeBillVO(), "");
                                        if(baseResult.getCode().equals("000000")){
                                            logger.info("内部对账一般缴款书电子票发送成功，票号："+cbv.getBillnum());
                                        }else{
                                            logger.info("内部对账一般缴款书电子票发送失败，票号："+cbv.getBillnum());
                                        }
                                    }
                                }
                                bankCheckResultMapper.saveChargeBill(cbv);
                            }catch(Exception e) {
                                logger.info("一般缴款书电子票错误信息="+e);
                            }
                        }
                        read.close();
                    }
                    if(i==2){  //一般缴款书手工票
                        ChargeBillHandCheckVO chcv=new ChargeBillHandCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            //  	String temp=lineTxt.replace(" ","");
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            chcv.setNum(s[0].toString());
                            chcv.setKeyword(Integer.parseInt(s[1].toString()));
                            chcv.setBillnum(s[2].toString());
                            chcv.setEticketnum(s[3].toString());
                            chcv.setCantonid(Integer.parseInt(s[4].toString()));
                            chcv.setUnitid(Integer.parseInt(s[5].toString()));
                            if(s[6].toString()!=null&&!"".equals(s[6].toString()))
                            {
                                chcv.setHallid(Integer.parseInt(s[6].toString()));
                            }
                            chcv.setFilldate(s[7].toString());
                            chcv.setPayer(s[8].toString());
                            chcv.setPayeraccount(s[9].toString());
                            chcv.setPayerbank(s[10].toString());
                            chcv.setBankid(Integer.parseInt(s[11].toString()));
                            chcv.setPayee(s[12].toString());
                            chcv.setPayeeaccount(s[13].toString());
                            chcv.setPayeebank(s[14].toString());
                            chcv.setMemo(s[15].toString());
                            chcv.setVertifycode(s[16].toString());
                            chcv.setOriginfund(Double.parseDouble(s[17].toString()));
                            if(s[18].toString()!=null&&!"".equals(s[18].toString()))
                            {
                                chcv.setIsscale(Integer.parseInt(s[18].toString()));
                            }
                            if(s[19].toString()!=null&&!"".equals(s[19].toString()))
                            {
                                chcv.setIshand(Integer.parseInt(s[19].toString()));
                            }
                            chcv.setPaybankdt(s[20].toString());
                            chcv.setBankaffirm(s[21].toString());
                            chcv.setBankstation(s[22].toString());
                            if(s[23].toString()!=null&&!"".equals(s[23].toString())) {
                                chcv.setIswaitaffirm(Integer.parseInt(s[23].toString()));
                            }
                            chcv.setWritename(s[24].toString());
                            chcv.setWritedate(s[25].toString());
                            if(s[26].toString()!=null&&!"".equals(s[26].toString())) {
                                chcv.setPaywayid(Integer.parseInt(s[26].toString()));
                            }
                            int scale=0;
                            if(s[27].toString()!=null&&!"".equals(s[27].toString())) {
                                scale=Integer.parseInt(s[27].toString());
                            }
                            int temnum=11;
                            List<ChargeBillHandDetailCheckVO> list =new ArrayList<ChargeBillHandDetailCheckVO>();
                            for(int j=0;j<scale;j++)
                            {
                                ChargeBillHandDetailCheckVO chbcv=new ChargeBillHandDetailCheckVO();
                                if(s[temnum*j+28].toString()!=null&&!"".equals(s[temnum*j+28].toString()))
                                {
                                    chbcv.setDetailid(Integer.parseInt(s[temnum*j+28].toString()));
                                }
                                if(s[temnum*j+29].toString()!=null&&!"".equals(s[temnum*j+29].toString()))
                                {
                                    chbcv.setFromitemid(Integer.parseInt(s[temnum*j+29].toString()));
                                }
                                chbcv.setItemstandtype(s[temnum*j+30].toString());
                                chbcv.setItemcode(s[temnum*j+31].toString());
                                chbcv.setItemname(s[temnum*j+32].toString());
                                chbcv.setMeasureunit(s[temnum*j+33].toString());
                                if(s[temnum*j+34].toString()!=null&&!"".equals(s[temnum*j+34].toString())) {
                                    chbcv.setOriginfund(Double.parseDouble(s[temnum*j+34].toString()));
                                }
                                if(s[temnum*j+35].toString()!=null&&!"".equals(s[temnum*j+35].toString())) {
                                    chbcv.setCurrentfund(Double.parseDouble(s[temnum*j+35].toString()));
                                }
                                if(s[temnum*j+36].toString()!=null&&!"".equals(s[temnum*j+36].toString())) {
                                    chbcv.setProvincescale(Double.parseDouble(s[temnum*j+36].toString()));
                                }
                                if(s[temnum*j+37].toString()!=null&&!"".equals(s[temnum*j+37].toString())) {
                                    chbcv.setCityscale(Double.parseDouble(s[temnum*j+37].toString()));
                                }
                                if(s[temnum*j+38].toString()!=null&&!"".equals(s[temnum*j+38].toString())) {
                                    chbcv.setAmount(Double.parseDouble(s[temnum*j+38].toString()));
                                }
                                list.add(chbcv);
                            }
                            try {
                                if(chcv.getIswaitaffirm()!=1){
                                    if(bankCheckMapper.findchargebillIsHandCount(chcv.getBillnum(), paybankdt1)==0){
                                        if(bankCheckResultMapper.isResult(1,1,chcv.getBillnum(),chcv.getBankstation(),paybankdt1)==0){
                                            long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                            bankCheckResultMapper.insertCheckResult(studentid,chcv.getBillnum(),chcv.getBankstation(),paybankdt1,1,2);
                                        }
                                        StringBuffer buf = new StringBuffer();
                                        String list_xml=createListXml(list);
                                        buf.append("<bill>");
                                        buf.append("<keyword>82</keyword>");
                                        buf.append("<billnum>");
                                        buf.append(chcv.getBillnum());
                                        buf.append("</billnum>");
                                        buf.append("<eticketnum></eticketnum>");
                                        buf.append("<cantonid>");
                                        buf.append(chcv.getCantonid());
                                        buf.append("</cantonid>");
                                        buf.append("<unitid>");
                                        buf.append(chcv.getUnitid());
                                        buf.append("</unitid>");
                                        buf.append("<hallid></hallid>");
                                        buf.append("<filldate>");
                                        buf.append(chcv.getFilldate());
                                        buf.append("</filldate>");
                                        buf.append("<payer>");
                                        buf.append(chcv.getPayer());
                                        buf.append("</payer>");
                                        buf.append("<payeraccount>");
                                        buf.append(chcv.getPayeraccount());
                                        buf.append("</payeraccount>");
                                        buf.append("<payerbank>");
                                        buf.append(chcv.getPayerbank());
                                        buf.append("</payerbank>");
                                        buf.append("<bankid>");
                                        buf.append(chcv.getBankid());
                                        buf.append("</bankid>");
                                        buf.append("<payee>");
                                        buf.append(chcv.getPayee());
                                        buf.append("</payee>");
                                        buf.append("<payeeaccount>");
                                        buf.append(chcv.getPayeeaccount());
                                        buf.append("</payeeaccount>");
                                        buf.append("<payeebank>");
                                        buf.append(chcv.getPayeebank());
                                        buf.append("</payeebank>");
                                        buf.append("<memo></memo>");
                                        buf.append("<vertifycode></vertifycode>");
                                        buf.append("<originfund>");
                                        buf.append(chcv.getOriginfund());
                                        buf.append("</originfund>");
                                        buf.append("<isscale>0</isscale>");
                                        buf.append("<ishand>1</ishand>");
                                        buf.append("<paybankdt>");
                                        buf.append(chcv.getPaybankdt());
                                        buf.append("</paybankdt>");
                                        buf.append("<bankaffirm>");
                                        buf.append(chcv.getBankaffirm());
                                        buf.append("</bankaffirm>");
                                        buf.append("<bankstation>"+chcv.getBankstation()+"</bankstation>");
                                        buf.append("<paywayid>");
                                        buf.append(chcv.getPaywayid());
                                        buf.append("</paywayid>");
                                        buf.append("<iswaitaffirm>0</iswaitaffirm>");
                                        buf.append("<writename>");
                                        buf.append(chcv.getWritename());
                                        buf.append("</writename>");
                                        buf.append("<writedate>");
                                        buf.append(chcv.getWritedate());
                                        buf.append("</writedate>");
                                        buf.append("<details>");
                                        buf.append(list_xml);
                                        buf.append("</details>");
                                        buf.append("</bill>");
                                        String xml = buf.toString();
                                        BaseResult baseResult = chargeBillService.setChargeBillManual(xml, "");
                                        if(baseResult.getCode().equals("000000")){
                                            logger.info("内部对账一般缴款书手工票发送成功，票号："+chcv.getBillnum());
                                        }else{
                                            logger.info("内部对账一般缴款书手工票发送失败，票号："+chcv.getBillnum());
                                        }
                                    }
                                }
                                bankCheckResultMapper.saveChargeBillHand(chcv);
                            }catch(Exception e){
                                logger.info("错误信息="+e.toString());
                            }
                        }
                        read.close();
                    }
                    if(i==3){  //交警罚没
                        IllegalactivityInfoCheckVO iiv=new IllegalactivityInfoCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            iiv.setNum(s[0].toString());
                            iiv.setBillnum(s[1].toString());
                            iiv.setAccountcode(s[2].toString());
                            iiv.setIsnohere(Integer.parseInt(s[3].toString()));
                            iiv.setIsspecialbill(Integer.parseInt(s[4].toString()));
                            iiv.setSpecialbillnum(s[5].toString());
                            iiv.setPaybankdt(s[6].toString());
                            iiv.setBankaffirm(s[7].toString());
                            iiv.setBankstation(s[8].toString());
                            iiv.setPaywaycode(s[9].toString());
                            try {
                                if(bankCheckMapper.findIllActInfoCheckBill(iiv.getBillnum(),paybankdt1)==0){
                                    if(bankCheckResultMapper.isResult(1,3,iiv.getBillnum(),iiv.getBankstation(),paybankdt1)==0){
                                        long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                        bankCheckResultMapper.insertCheckResult(studentid,iiv.getBillnum(),iiv.getBankstation(),paybankdt1,1,3);
                                    }
                                    BaseResult baseResult = punishService.setPayInfo(iiv.getBillnum(), iiv.getAccountcode(), iiv.getIsnohere(),
                                            iiv.getIsspecialbill(), iiv.getSpecialbillnum(), iiv.getPaybankdt(),
                                            iiv.getBankaffirm(), iiv.getBankstation(), iiv.getPaywaycode(), "00", "");
                                    if(baseResult.getCode().equals("000000")){
                                        logger.info("内部对账交罚发送成功，票号："+iiv.getBillnum());
                                    }else{
                                        logger.info("内部对账交罚发送失败，票号："+iiv.getBillnum());
                                    }
                                }
                                bankCheckResultMapper.saveIllactiInfo(iiv);
                            }catch(Exception e) {
                                logger.info("错误信息="+e.toString());
                            }
                        }
                        read.close();
                    }
                    if(i==4) { //学校缴费
                        StudentCheckVO scv=new StudentCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            scv.setNum(s[0].toString());
                            scv.setStudentnum(s[1].toString());
                            scv.setPaybankdt(s[2].toString());
                            scv.setBankaffirm(s[3].toString());
                            scv.setBankstation(s[4].toString());
                            try {
                                if(bankCheckMapper.findstudentBillCount(scv.getStudentnum(),paybankdt1)==0){
                                    if(bankCheckResultMapper.isResult(1,4,scv.getStudentnum(),scv.getBankstation(),paybankdt1)==0){
                                        long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                        bankCheckResultMapper.insertCheckResult(studentid,scv.getStudentnum(),scv.getBankstation(),paybankdt1,1,4);
                                    }
                                    BaseResult baseResult = studentService.setStudentPayInfo(scv.getStudentnum(),
                                            scv.getPaybankdt(),
                                            scv.getBankaffirm(),
                                            scv.getBankstation(), "00", "");
                                    if(baseResult.getCode().equals("000000")){
                                        logger.info("内部对账学校发送成功，票号："+scv.getStudentnum());
                                    }else{
                                        logger.info("内部对账学校发送失败，票号："+scv.getStudentnum());
                                    }
                                }
                                bankCheckResultMapper.saveStudentBill(scv);
                            }catch(Exception e) {
                                logger.info("错误信息="+e.toString());
                            }
                        }
                        read.close();
                    }
                    if(i==5) {  //划解国库

                        FiscPayInfoCheckVO fcv=new FiscPayInfoCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            //  	String temp=lineTxt.replace(" ","");
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            fcv.setNum(s[0].toString());
                            fcv.setBillnum(s[1].toString());
                            fcv.setPaybankdt(s[2].toString());
                            fcv.setBankaffirm(s[3].toString());
                            fcv.setBankstation(s[4].toString());
                            try {
                                if(bankCheckMapper.findfiscCheckBill(fcv.getBillnum(),paybankdt1)==0){
                                    if(bankCheckResultMapper.isResult(1,5,fcv.getBillnum(),fcv.getBankstation(),paybankdt1)==0){
                                        long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                        bankCheckResultMapper.insertCheckResult(studentid,fcv.getBillnum(),fcv.getBankstation(),paybankdt1,1,5);
                                    }
                                    BaseResult baseResult = fiscService.setFiscPayInfo(fcv.getBillnum(),
                                            fcv.getBankaffirm(),
                                            fcv.getPaybankdt(),
                                            fcv.getBankstation(), "");
                                    if(baseResult.getCode().equals("000000")){
                                        logger.info("内部对账国库发送成功，票号："+fcv.getBillnum());
                                    }else{
                                        logger.info("内部对账国库发送失败，票号："+fcv.getBillnum());
                                    }
                                }
                                bankCheckResultMapper.saveFiscPayInfo(fcv);
                            }catch(Exception e) {
                                logger.info("错误信息="+e.toString());
                            }
                        }
                        read.close();
                    }
                    if(i==6){  //划解专户

                        SpecialPayInfoCheckVO scv=new SpecialPayInfoCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            //  	String temp=lineTxt.replace(" ","");
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            scv.setNum(s[0].toString());
                            scv.setBillnum(s[1].toString());
                            scv.setPaybankdt(s[2].toString());
                            scv.setBankaffirm(s[3].toString());
                            scv.setBankstation(s[4].toString());
                            try{
                                if(bankCheckMapper.findPaySpeciCouny(scv.getBillnum(),paybankdt1)==0){
                                    if(bankCheckResultMapper.isResult(1,6,scv.getBillnum(),scv.getBankstation(),paybankdt1)==0){
                                        long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                        bankCheckResultMapper.insertCheckResult(studentid,scv.getBillnum(),scv.getBankstation(),paybankdt1,1,6);
                                    }
                                    BaseResult baseResult = specialService.setSpecialPayInfo(scv.getBillnum(),
                                            scv.getBankaffirm(),
                                            scv.getPaybankdt(),
                                            scv.getBankstation(), "");
                                    if(baseResult.getCode().equals("000000")){
                                        logger.info("内部对账专户发送成功，票号："+scv.getBillnum());
                                    }else{
                                        logger.info("内部对账专户发送失败，票号："+scv.getBillnum());
                                    }
                                }
                                bankCheckResultMapper.saveSpeciPayInfo(scv);
                            }catch(Exception e){
                                logger.info("错误信息="+e.toString());
                            }
                        }
                        read.close();
                    }
                    if(i==7){  //划解分成
                        DividePayInfoCheckVO dcv=new DividePayInfoCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            //  	String temp=lineTxt.replace(" ","");
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            dcv.setNum(s[0].toString());
                            dcv.setDividebillnum(s[1].toString());
                            dcv.setPaybankdt(s[2].toString());
                            dcv.setBankaffirm(s[3].toString());
                            dcv.setBankstation(s[4].toString());
                            try {
                                if(bankCheckMapper.findDividePayCount(dcv.getDividebillnum(),paybankdt1)==0){
                                    if(bankCheckResultMapper.isResult(1,7,dcv.getDividebillnum(),dcv.getBankstation(),paybankdt1)==0){
                                        long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                        bankCheckResultMapper.insertCheckResult(studentid,dcv.getDividebillnum(),dcv.getBankstation(),paybankdt1,1,7);
                                    }
                                    BaseResult baseResult = divideService.setDividePayInfo(dcv.getDividebillnum(),
                                            dcv.getBankaffirm(),
                                            dcv.getPaybankdt(),
                                            dcv.getBankstation());
                                    if(baseResult.getCode().equals("000000")){
                                        logger.info("内部对账分成发送成功，票号："+dcv.getDividebillnum());
                                    }else{
                                        logger.info("内部对账分成发送失败，票号："+dcv.getDividebillnum());
                                    }
                                }
                                bankCheckResultMapper.saveDividPayInfo(dcv);
                            }catch(Exception e) {
                                logger.info("错误信息="+e.toString());
                            }
                        }
                        read.close();
                    }
                    if(i==8){  //划解二八分成
                        IllegalactivityScaleCheckVO iscv=new IllegalactivityScaleCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            //  	String temp=lineTxt.replace(" ","");
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            iscv.setNum(s[0].toString());
                            iscv.setBillnum(s[1].toString());
                            iscv.setDetailno(s[2].toString());
                            iscv.setPaybankdt(s[3].toString());
                            iscv.setBankaffirm(s[4].toString());
                            iscv.setBankstation(s[5].toString());
                            try {
                                if(bankCheckMapper.findPayScaleBillCheck(iscv.getBillnum(),paybankdt1)==0){
                                    if(bankCheckResultMapper.isResult(1,8,iscv.getBillnum(),iscv.getBankstation(),paybankdt1)==0){
                                        long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                        bankCheckResultMapper.insertCheckResult(studentid,iscv.getBillnum(),iscv.getBankstation(),paybankdt1,1,8);
                                    }
                                    BaseResult baseResult = payScaleBillService.setIllegalactivityScaleBankaffirm(iscv.getPayScaleBillVO());
                                    if(baseResult.getCode().equals("000000")){
                                        logger.info("内部对账二八分成发送成功，票号："+iscv.getBillnum());
                                    }else{
                                        logger.info("内部对账二八分成发送失败，票号："+iscv.getBillnum());
                                    }
                                }
                                bankCheckResultMapper.saveIllActiScal(iscv);
                            }catch(Exception e) {
                                logger.info("错误信息="+e.toString());
                            }
                        }
                        read.close();
                    }
                    if(i==9){  //退付书
                        BackBillDepositCheckVO bbcv=new BackBillDepositCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            bbcv.setNum(s[0].toString());
                            bbcv.setBackbillnum(s[1].toString());
                            bbcv.setPaybankdt(s[2].toString());
                            bbcv.setBankaffirm(s[3].toString());
                            bbcv.setBankstation(s[4].toString());
                            try {
                                if(bankCheckMapper.findBackPaybillInfo(bbcv.getBackbillnum(),paybankdt1)==0){
                                    if(bankCheckResultMapper.isResult(1,9,bbcv.getBackbillnum(),bbcv.getBankstation(),paybankdt1)==0){
                                        long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                        bankCheckResultMapper.insertCheckResult(studentid,bbcv.getBackbillnum(),bbcv.getBankstation(),paybankdt1,1,9);
                                    }
                                    BaseResult baseResult = backBillService.setBackBillDeposit(bbcv.getBackpaybillVO(), "");
                                    if(baseResult.getCode().equals("000000")){
                                        logger.info("内部对账退付书发送成功，票号："+bbcv.getBackbillnum());
                                    }else{
                                        logger.info("内部对账退付书发送失败，票号："+bbcv.getBackbillnum());
                                    }
                                }
                                bankCheckResultMapper.saveBackBillDep(bbcv);
                            }catch(Exception e) {
                                logger.info("错误信息="+e.toString());
                            }
                        }
                        read.close();
                    }
                    if(i==10){  //跨省交罚
                        IllegalactivityCrossPayInfoCheckVO icpc=new IllegalactivityCrossPayInfoCheckVO();
                        while ((lineTxt = bufferedReader.readLine()) != null) {
                            //  	String temp=lineTxt.replace(" ","");
                            String temp=lineTxt;
                            String[] s=temp.split("\\|");
                            icpc.setNum(s[0].toString());
                            icpc.setBillnum(s[1].toString());
                            icpc.setOccurdatetime(s[2].toString());
                            icpc.setOpterdatetime(s[3].toString());
                            icpc.setCertificatenum(s[4].toString());
                            icpc.setOccurname(s[5].toString());
                            icpc.setPayeeaccountnum(s[6].toString());
                            icpc.setTrafficunitnum(s[7].toString());
                            icpc.setFunds(Double.parseDouble(s[8].toString()));
                            icpc.setLatefee(Double.parseDouble(s[9].toString()));
                            icpc.setBankid(Integer.parseInt(s[10].toString()));
                            icpc.setPayregion(s[11].toString());
                            icpc.setBreakaddress(s[12].toString());
                            icpc.setPaychannels(s[13].toString());
                            icpc.setRemark(s[14].toString());
                            icpc.setPaybankdt(s[15].toString());
                            icpc.setBankaffirm(s[16].toString());
                            icpc.setBankstation(s[17].toString());

                            try{
                                if(bankCheckMapper.findillActInfoCount(icpc.getBillnum(),paybankdt1)==0){
                                    if(bankCheckResultMapper.isResult(1,10,icpc.getBillnum(),icpc.getBankstation(),paybankdt1)==0){
                                        long studentid = sequenceService.getNextSeq("FSCHECKRESULTSEQ");
                                        bankCheckResultMapper.insertCheckResult(studentid,icpc.getBillnum(),icpc.getBankstation(),paybankdt1,1,10);
                                    }
                                    //添加数据验证
                                    String errnum="";
                                    BaseResult baseResult = new BaseResult("01","");
                                    if(icpc.getBillnum()==null||"".equals(icpc.getBillnum().trim())){
                                        errnum="errnum=2,";
                                    }
                                    else if(icpc.getPaybankdt()==null||"".equals(icpc.getPaybankdt().trim())){
                                        errnum="errnum=3,";
                                    }
                                    else if(icpc.getBankaffirm()==null||"".equals(icpc.getBankaffirm().trim())){
                                        errnum="errnum=4,";
                                    }
                                    else if(icpc.getBankstation()==null||"".equals(icpc.getBankstation().trim())){
                                        errnum="errnum=5,";
                                    }
                                    else if("".equals(icpc.getBankid()+"")){
                                        errnum="errnum=6,";
                                    }
                                    else if(icpc.getTrafficunitnum()==null||"".equals(icpc.getTrafficunitnum().trim())){
                                        errnum="errnum=7,";
                                    }
                                    else if(icpc.getFunds()<icpc.getLatefee()){
                                        errnum="errnum=8,";
                                    }
                                    else{
                                        baseResult=illegalactivityinfoService.setIllegalactivityCrossPayInfo(icpc.getIllegalactivityinfoVO());
                                    }
                                    if(baseResult.getCode().equals("000000")){
                                        logger.info("内部对账跨省交罚发送成功，票号："+icpc.getBillnum());
                                    }else{
                                        logger.info(errnum+"内部对账跨省交罚发送失败，票号："+icpc.getBillnum());
                                    }
                                }
                                bankCheckResultMapper.saveIllcrossPay(icpc);
                            }catch(Exception e){
                                logger.info("错误信息="+e.toString());
                            }
                        }
                        read.close();
                    }
                }else {
                    System.out.println("找不到指定"+filePath+"的文件");
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            logger.info("错误信息="+e);
        }

    }

    public String createListXml(List<ChargeBillHandDetailCheckVO> list){
        StringBuffer buf = new StringBuffer();
        for(int i=0;i<list.size();i++){
            ChargeBillHandDetailCheckVO cbcv= list.get(i);
            buf.append("<detail>");
            buf.append("<detailid>0</detailid>");
            buf.append("<fromitemid>");
            buf.append(cbcv.getFromitemid());
            buf.append("</fromitemid>");
            buf.append("<itemstandtype>");
            buf.append(cbcv.getItemstandtype());
            buf.append("</itemstandtype>");
            buf.append("<itemcode>");
            buf.append(cbcv.getItemcode());
            buf.append("</itemcode>");
            buf.append("<itemname>");
            buf.append(cbcv.getItemname());
            buf.append("</itemname>");
            buf.append("<measureunit></measureunit>");
            buf.append("<originfund>");
            buf.append(cbcv.getOriginfund());
            buf.append("</originfund>");
            buf.append("<currentfund>");
            buf.append(cbcv.getOriginfund());
            buf.append("</currentfund>");
            buf.append("<provincescale>0.00</provincescale>");
            buf.append("<cityscale>0.00</cityscale>");
            buf.append("<amount>");
            buf.append(cbcv.getAmount());
            buf.append("</amount>");
            buf.append("</detail>");
        }
        return buf.toString();

    }

    private String getCheckBillID(int purpose, String id) {
        if (id == null || id.length() == 0) {
            id = purpose + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        }
        return id;
    }
}

